package com.lee.controller;

import org.json.JSONException;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;
import org.springframework.web.bind.annotation.RestController;

import com.lee.entity.UserInfo;
import com.lee.service.UserInfoService;
import com.lee.tools.JsonResult;
import com.lee.tools.TokenJwt;

@RestController
public class Jwt {

	@Autowired
	private UserInfoService userinfoservice;

	@RequestMapping(value = "/user/register", method = RequestMethod.POST)
	public String register(UserInfo userinfo) throws JSONException {
		if (userinfoservice.addUserInfo(userinfo) == true) {
			return JsonResult.fillResultString(0, "注册成功", "");
		} else {
			return JsonResult.fillResultString(1, "注册失败", "");
		}
	}

	@RequestMapping(value = "/user/login", method = RequestMethod.POST)
	public String validate(UserInfo userinfo) throws JSONException {
		// 获取用户输入的手机号和密码
		String tel = userinfo.getTel();
		String password = userinfo.getPass();

		if (userinfoservice.validateUserInfo(tel) == true) {

			// 从数据库获取用户注册时的手机号和密码
			String re_pass = userinfoservice.findUserInfo(tel).getPass();

			if (password.equals(re_pass)) {
				int id = userinfoservice.findUserInfo(tel).getUser_id();
				String ids = String.valueOf(id);

				// token有效期为一周
				String token = TokenJwt.createJWT(ids, 6048000);
				return JsonResult.fillTokenString(0, "登录成功", token, "");
			} else {
				return JsonResult.fillResultString(1, "登录失败", "");
			}
		} else {
			return JsonResult.fillResultString(2, "未注册，请先注册", "");
		}

	}

	@RequestMapping(value = "/user/updatepass", method = RequestMethod.PUT)
	public String UpdatePass(UserInfo userinfo) throws JSONException {
		// 获取用户请求时的token

		String post_token = userinfo.getToken();
		try {
			if (post_token.equals(null)) {
				return JsonResult.fillResultString(2, "请先登录", "");
			} else {
				// 获取token里的用户Id
				String user_id = TokenJwt.parseJWT(post_token).getId();
				int id = Integer.parseInt(user_id);
				userinfo.setUser_id(id);

				if (userinfoservice.updatePassword(userinfo) == true) {
					return JsonResult.fillResultString(0, "修改密码成功", "");
				} else {
					return JsonResult.fillResultString(1, "修改密码失败", "");
				}

			}
		} catch (Exception e) {
			return JsonResult.fillResultString(3, "token错误", "");
		}

	}
}
